package com.yx1996.dao.impl;

import com.yx1996.dao.UserDao;
import com.yx1996.domain.User;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.hibernate.query.Query;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import java.util.List;

/**
 //spring整合hibernate对数据库的操作
 */
public class UserDaoImpl extends HibernateDaoSupport  implements UserDao {


    @Override
    //查找用户
    public User getUserByCode(final User u) {

        //hql查询
       return this.getHibernateTemplate().execute(new HibernateCallback<User>() {

            @Override
            public User doInHibernate(Session session) throws HibernateException {
                String hql = "from User where user_code = ?1";
                Query query = session.createQuery(hql).setParameter(1, u.getUser_code());
                return (User) query.uniqueResult();
            }
        });

        /*//criteria离线查询
        DetachedCriteria dc = new DetachedCriteria.forClass(User.class);
        dc.add(Restrictions.eq("user_code",u.getUser_code()));
        List<User> list = (List<User>) this.getHibernateTemplate().findByCriteria(dc);
        if(list !=null&&list.size()>0){
            return list.get(0);
        }else{
            return null;
        }*/
    }

    @Override
    //保存用户
    public void saveUser(final User u) {

        //hql查询
        this.getHibernateTemplate().save(u);

    }
}
